package com.example.supernote.ui.note.components

import android.Manifest
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CameraAlt
import androidx.compose.material.icons.filled.Upload
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import com.example.supernote.R
import com.example.supernote.ui.components.UniformButton
import com.example.supernote.ui.components.UniformDialog
import com.example.supernote.ui.components.UniformPreviewBody
import com.example.supernote.ui.components.UniformPreviewFooter
import com.example.supernote.ui.components.UniformProgressBar
import com.example.supernote.ui.components.UniformToast
import com.example.supernote.ui.note.utils.SelectPhotoContract
import com.example.supernote.ui.note.utils.TakePhotoContract
import com.example.supernote.ui.note.utils.getBase64
import com.example.supernote.ui.note.utils.getFinalTemplate
import com.example.supernote.ui.utils.getPermissionLauncher
import com.example.supernote.ui.utils.getShowInfos

@Composable
fun ShowTextOcrDialog(
    onCancel: () -> Unit,
    onGenerate: ((String) -> Unit, String, String) -> Unit,
    onConfirm: (ocrText: String) -> Unit
) {
    val context = LocalContext.current
    // 图片
    var imageUri: Uri? by remember { mutableStateOf(null) }

    // 文本识别配置
    var newLine by remember { mutableStateOf(true) }
    var template by remember { mutableStateOf("") }
    var isGenerated by remember { mutableStateOf(false) }
    val dialogTitle = stringResource(R.string.note_ocr)
    val showInfos = getShowInfos(dialogTitle)
    var uploadPreview by remember { mutableStateOf(false) }
    var cameraPreview by remember { mutableStateOf(false) }

    UniformDialog(
        title = dialogTitle,
        onCancel = onCancel,
        body = {
            val uploadLauncher =
                rememberLauncherForActivityResult(contract = SelectPhotoContract()) {
                    it?.let { uri ->
                        template = ""
                        imageUri = uri
                        uploadPreview = true
                        cameraPreview = false
                    }
                }
            val cameraLauncher = rememberLauncherForActivityResult(contract = TakePhotoContract()) {
                it?.let { uri ->
                    template = ""
                    imageUri = uri
                    uploadPreview = false
                    cameraPreview = true
                }
            }
            val uploadPermission = getPermissionLauncher({ uploadLauncher.launch(null) })
            val cameraPermission = getPermissionLauncher({ cameraLauncher.launch(null) })

            if (uploadPreview || cameraPreview) {
                if (template.isEmpty()) {
                    UniformPreviewBody(
                        title = stringResource(R.string.note_preview_select),
                        sourceUri = imageUri
                    )
                } else {
                    val getHtml: @Composable () -> String = {
                        val ctx = com.example.supernote.model.note.context.Context()
                        ctx.article = TextFieldValue(getFinalTemplate(template))
                        ctx.parseContext()
                    }

                    UniformPreviewBody(
                        title = dialogTitle,
                        html = getHtml()
                    )
                }
                Row(
                    horizontalArrangement = Arrangement.Start,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Checkbox(checked = newLine, onCheckedChange = {
                        newLine = it
                    }, enabled = !isGenerated)
                    Text(text = stringResource(R.string.note_ocr_mode))
                    Spacer(modifier = Modifier.weight(1f))
                }
                if (isGenerated) {
                    UniformProgressBar(showInfos["progressInfo"]!!, "liner")
                }
            }
            if (!isGenerated) {
                Row {
                    UniformButton(
                        modifier = Modifier.weight(1f),
                        onClick = { uploadPermission.launch(Manifest.permission.READ_EXTERNAL_STORAGE) },
                        imageVector = Icons.Filled.Upload,
                        text = if (uploadPreview) stringResource(R.string.note_upload_after) else stringResource(
                            R.string.note_upload_before
                        )
                    )
                    Spacer(modifier = Modifier.width(5.dp))
                    UniformButton(
                        modifier = Modifier.weight(1f),
                        onClick = { cameraPermission.launch(Manifest.permission.CAMERA) },
                        imageVector = Icons.Filled.CameraAlt,
                        text = if (cameraPreview) stringResource(R.string.note_take_image_after) else stringResource(
                            R.string.note_take_image_before
                        )
                    )
                }
            }
        }
    ) {
        val warn = stringResource(R.string.note_text_warning)
        UniformPreviewFooter(
            template = template,
            isGenerated = isGenerated,
            aiMode = showInfos["aiMode"]!!,
            confirmButtonText = showInfos["confirmButtonText"]!!,
            onCancel = {
                onCancel()
                uploadPreview = false; cameraPreview = false
                template = ""
            },
            onConfirm = {
                onConfirm(template)
                UniformToast(context, showInfos["resultTip"]!!)
            },
            onGenerate = {
                imageUri?.let {
                    val imageBase64 = getBase64(imageUri!!, context.contentResolver)
                    template = ""
                    isGenerated = true
                    onGenerate({
                        template = it
                        isGenerated = false
                    }, imageBase64, if (newLine) "\n\n" else "")
                } ?: run {
                    UniformToast(context, warn)
                }
            }
        )
    }
}